package com.orangeandbronze.demos.mapreduce;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.tools.pipeline.Job3;
import com.google.appengine.tools.pipeline.Value;

public class UpdateFileMetadataJob extends Job3<Void, String, String, String> {

	private static final long serialVersionUID = -6035522490119305448L;

	// private transient DatastoreMutationPool pool;

	@Override
	public Value<Void> run(String type, String key, String pipelineId)
			throws Exception {
		// pool = DatastoreMutationPool.forWorker(this);
		DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
		try {
			Entity entity = datastoreService.get(
					KeyFactory.createKey(
							KeyFactory.createKey(
									"user", UserServiceFactory.getUserService().getCurrentUser().getUserId()),
							FileMetadata.KIND, key));
			String propertyName = null;
			switch (type) {
			case "WordCount":
				propertyName = "wordcount_jobId";
				break;
			case "Index":
				propertyName = "index_jobId";
				break;
			case "Phrases":
				propertyName = "phrases_jobId";
				break;
			default:
				break;
			}
			if (propertyName != null) {
				entity.setProperty(propertyName, pipelineId);
				datastoreService.put(entity);
			}
		} catch (EntityNotFoundException e) {
			// TODO: handle exception
		}
		return null;
	}

}
